package com.lion.seaman.server.controller;

import com.lion.seaman.common.tools.JsonTools;
import com.lion.seaman.common.tools.StringTools;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class BaseController {
    private Logger log = Logger.getLogger(BaseController.class);

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public void setCharacterEncoding(String characterEncoding) {
        HttpServletRequest request = getRequest();
        try {
            request.setCharacterEncoding(characterEncoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    public <T> T getParam(String key, T defaultValue) {
        HttpServletRequest request = getRequest();
        Object value = request.getParameter(key);
        if (value == null) {
            return defaultValue;
        }
        String val = value.toString();
        return StringTools.coverTo(val, defaultValue);
    }

    public <T> T getAttr(String key, T defaultValue) {
        HttpServletRequest request = getRequest();
        Object value = request.getAttribute(key);
        if (value == null) {
            return defaultValue;
        }
        String val = value.toString();
        return StringTools.coverTo(val, defaultValue);
    }

    public void outJson(Object msg) {
        out(JsonTools.beanToJson(msg), "application/json; charset=utf-8");
    }

    public void outString(String str) {
        out(str, "text/plain;charset=utf-8");
    }

    public void outHtml(String str) {
        out(str, "text/html;charset=utf-8");
    }


    public void out(Object msg, String contentType) {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        try {
            PrintWriter writer = response.getWriter();
            writer.print(msg);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }


}
